

package com.zdkj.subway.support.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.mybatis.wrapper.CustomQueryWrapper;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.support.entity.SwPmDeviceOperationCode;
import com.zdkj.subway.support.entity.SwPmTvmCode;
import com.zdkj.subway.support.service.SwPmDeviceOperationCodeService;
import com.zdkj.subway.support.util.UploadDataListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;


/**
 * 设备操作号基础参数表
 *
 * @author cuilei
 * @date 2020-05-28 14:03:33
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swpmdeviceoperationcode")
@Api(value = "swpmdeviceoperationcode", tags = "设备操作号基础参数表管理")
public class SwPmDeviceOperationCodeController {

    private final SwPmDeviceOperationCodeService swPmDeviceOperationCodeService;

    /**
     * 分页查询
     *
     * @param page                    分页对象
     * @param swPmDeviceOperationCode 设备操作号基础参数表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwPmDeviceOperationCodePage(Page page, SwPmDeviceOperationCode swPmDeviceOperationCode) {
        /*if (!SecurityUtils.getUser().getBelongToLine()) {
            QueryWrapper<SwPmDeviceOperationCode> queryWrapper = Wrappers.query(swPmDeviceOperationCode);
            queryWrapper.lambda().eq(SwPmDeviceOperationCode::getLineCode, SecurityUtils.getUser().getLineCode());
            queryWrapper.lambda().eq(SwPmDeviceOperationCode::getStationCode, SecurityUtils.getUser().getStationCode());
            return R.ok(swPmDeviceOperationCodeService.page(page, queryWrapper));
        }else{
            return R.ok(swPmDeviceOperationCodeService.page(page, Wrappers.query(swPmDeviceOperationCode)));
        }*/
        if (SecurityUtils.getUser().getBelongToLine()) {
            return R.ok(swPmDeviceOperationCodeService.page(page, Wrappers.query(swPmDeviceOperationCode)));
            
        }else if(swPmDeviceOperationCode.getQuerySource()!=null && "LC".equals(swPmDeviceOperationCode.getQuerySource())){
        	 return R.ok(swPmDeviceOperationCodeService.page(page, Wrappers.query(swPmDeviceOperationCode)));
        }else {
            QueryWrapper<SwPmDeviceOperationCode> queryWrapper = Wrappers.query(swPmDeviceOperationCode);
            queryWrapper.lambda().eq(SwPmDeviceOperationCode::getLineCode, SecurityUtils.getUser().getLineCode());
            queryWrapper.lambda().eq(SwPmDeviceOperationCode::getStationCode, SecurityUtils.getUser().getStationCode());
            return R.ok(swPmDeviceOperationCodeService.page(page, queryWrapper));
        }
    }

    /**
     * 线路管理分页查询
     *
     * @param page                    分页对象
     * @param swPmDeviceOperationCode 设备操作号基础参数表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/pageForLine")
    public R getSwPmDeviceOperationCodePageForLine(Page page, SwPmDeviceOperationCode swPmDeviceOperationCode) {
        QueryWrapper<SwPmDeviceOperationCode> queryWrapper = Wrappers.query(swPmDeviceOperationCode);
        queryWrapper.lambda().eq(SwPmDeviceOperationCode::getLineCode, SecurityUtils.getUser().getLineCode());
        return R.ok(swPmDeviceOperationCodeService.page(page, queryWrapper));
    }

    /**
     * 分页查询
     *
     * @param page                    分页对象
     * @param swPmDeviceOperationCode 设备操作号基础参数表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/queryByPage")
    public R queryByPage(Page page, SwPmDeviceOperationCode swPmDeviceOperationCode) {
        if (SecurityUtils.getUser().getBelongToLine()) {
            return R.ok(swPmDeviceOperationCodeService.queryByPage(page, (Wrapper) new CustomQueryWrapper(SwPmDeviceOperationCode.class)
                    .addDTO(swPmDeviceOperationCode)
                    .addAlis("a")
                    .init()
                    .eq("a.station_code", SecurityUtils.getUser().getStationCode())));
        } else {
            return R.ok(swPmDeviceOperationCodeService.queryByPage(page, new CustomQueryWrapper(SwPmDeviceOperationCode.class)
                    .addAlis("a")
                    .addDTO(swPmDeviceOperationCode)
                    .init()));
        }
    }

    /**
     * 通过id查询设备操作号基础参数表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swPmDeviceOperationCodeService.getById(id));
    }

    /**
     * 新增设备操作号基础参数表
     *
     * @param swPmDeviceOperationCode 设备操作号基础参数表
     * @return R
     */
    @ApiOperation(value = "新增设备操作号基础参数表", notes = "新增设备操作号基础参数表")
    //@SysLog("新增设备操作号基础参数表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('support_sw_pm_device_operation_code_add')")
    public R save(@RequestBody SwPmDeviceOperationCode swPmDeviceOperationCode) {
        List<SwPmDeviceOperationCode> deviceOperationCode = swPmDeviceOperationCodeService.list(Wrappers.<SwPmDeviceOperationCode>query().lambda()
                .eq(SwPmDeviceOperationCode::getLineCode, swPmDeviceOperationCode.getLineCode())
                .eq(SwPmDeviceOperationCode::getStationCode, swPmDeviceOperationCode.getStationCode())
                .eq(SwPmDeviceOperationCode::getOperationCode, swPmDeviceOperationCode.getOperationCode()));
        if (CollectionUtil.isNotEmpty(deviceOperationCode)) {
            return R.failed(swPmDeviceOperationCode.getLineCode()+"号线该车站设备操作号为"+swPmDeviceOperationCode.getOperationCode()+"的数据已存在,相同线路车站设备操作号不允许重复");
        }
        SwPmDeviceOperationCode defaultObj = ObjectUtils.getDefaultObj(SwPmDeviceOperationCode.class);
        BeanUtils.copyProperties(swPmDeviceOperationCode, defaultObj,
                ObjectUtils.getNullAndEmptyPropertyNames(swPmDeviceOperationCode));
        return R.ok(swPmDeviceOperationCodeService.save(defaultObj));
    }

    /**
     * 修改设备操作号基础参数表
     *
     * @param swPmDeviceOperationCode 设备操作号基础参数表
     * @return R
     */
    @ApiOperation(value = "修改设备操作号基础参数表", notes = "修改设备操作号基础参数表")
    //@SysLog("修改设备操作号基础参数表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('support_sw_pm_device_operation_code_edit')")
    public R updateById(@RequestBody SwPmDeviceOperationCode swPmDeviceOperationCode) {
        List<SwPmDeviceOperationCode> deviceOperationCode = swPmDeviceOperationCodeService.list(Wrappers.<SwPmDeviceOperationCode>query().lambda()
                        .eq(SwPmDeviceOperationCode::getLineCode, swPmDeviceOperationCode.getLineCode())
                        .eq(SwPmDeviceOperationCode::getStationCode, swPmDeviceOperationCode.getStationCode())
                        .eq(SwPmDeviceOperationCode::getOperationCode, swPmDeviceOperationCode.getOperationCode()));
        if (CollectionUtil.isNotEmpty(deviceOperationCode)) {
            for(SwPmDeviceOperationCode item : deviceOperationCode){
                if(!Objects.equals(swPmDeviceOperationCode.getId(),item.getId())){
                    return R.failed(swPmDeviceOperationCode.getLineCode()+"号线该车站设备操作号为"+swPmDeviceOperationCode.getOperationCode()+"的数据已存在,相同线路车站设备操作号不允许重复");
                }
            }
        }
        return R.ok(swPmDeviceOperationCodeService.updateById(swPmDeviceOperationCode));
    }


    /**
     * 通过id删除设备操作号基础参数表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除设备操作号基础参数表", notes = "通过id删除设备操作号基础参数表")
   // @SysLog("通过id删除设备操作号基础参数表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('support_sw_pm_device_operation_code_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swPmDeviceOperationCodeService.removeById(id));
    }

    /**
     * 导入设备操作号
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "导入设备操作号", notes = "导入设备操作号")
    //@SysLog("导入设备操作号")
    @PostMapping("import")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), SwPmDeviceOperationCode.class,
                    new UploadDataListener(swPmDeviceOperationCodeService, SwPmDeviceOperationCode.class)).sheet().doRead();
            return R.ok("导入成功");
        } catch (IOException e) {
            log.info(e.getMessage());
            return R.failed("导入失败");
        }
    }

    /**
     * 查询已启用的设备操作号
     *
     * @return
     */
    @ApiOperation(value = "查询已启用的设备操作号", notes = "查询已启用的设备操作号")
    //@SysLog("查询已启用的设备操作号")
    @GetMapping("/enabledList")
    public R getEnabledList() {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("status","1");
        if (SecurityUtils.getUser().getBelongToLine()) {
            queryWrapper.eq("station_code",SecurityUtils.getUser().getStationCode());
            return R.ok(swPmDeviceOperationCodeService.list(queryWrapper));
        } else {
            return R.ok(swPmDeviceOperationCodeService.list());
        }
    }

    /**
     * insertOrUpdate设备操作表
     * @param lineCode
     * @param stationCode
     * @param operationCode
     * @return R
     */
    @ApiOperation(value = "insert设备操作表", notes = "insertOrUpdate设备操作表")
    @GetMapping("/insertDeviceOperation/{lineCode}/{stationCode}/{operationCode}")
    public R insertDeviceOperation(@PathVariable("lineCode")String lineCode, @PathVariable("stationCode")String stationCode, @PathVariable("operationCode")String operationCode) {
        SwPmDeviceOperationCode swPmDeviceOperationCode = swPmDeviceOperationCodeService.getOne(Wrappers.<SwPmDeviceOperationCode>lambdaQuery()
                .eq(SwPmDeviceOperationCode::getLineCode, lineCode)
                .eq(SwPmDeviceOperationCode::getStationCode, stationCode)
                .eq(SwPmDeviceOperationCode::getOperationCode, operationCode)
                .eq(SwPmDeviceOperationCode::getDelFlag,"0"));
        if(ObjectUtil.isEmpty(swPmDeviceOperationCode)){
            SwPmDeviceOperationCode pmDeviceOperationCode = new SwPmDeviceOperationCode();
            pmDeviceOperationCode.setLineCode(lineCode);
            pmDeviceOperationCode.setStationCode(stationCode);
            pmDeviceOperationCode.setOperationCode(operationCode);
            pmDeviceOperationCode.setStatus("1");
            pmDeviceOperationCode.setDeptId(1);
            pmDeviceOperationCode.setCreatorId(1);
            pmDeviceOperationCode.setCreatorName("管理员");
            return R.ok(swPmDeviceOperationCodeService.save(pmDeviceOperationCode));
        }
        return R.ok();
    }
}
